package com.peng.leetcode.tree;

/**
 * PruneTree1
 * 剑指 Offer II 047. 二叉树剪枝
 * https://leetcode.cn/problems/pOCWxh/
 * <p>
 * Created on 2022/11/19
 *
 * @author lupeng
 */
public class PruneTree1 {

    public TreeNode pruneTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        if (isZero(root)) {
            return null;
        }
        if (isZero(root.left)) {
            root.left = null;
        } else {
            root.left = pruneTree(root.left);
        }
        if (isZero(root.right)) {
            root.right = null;
        } else {
            root.right = pruneTree(root.right);
        }
        return root;
    }


    public boolean isZero(TreeNode root) {
        if (root == null) {
            return true;
        }
        if (root.val != 0) {
            return false;
        }
        if (!isZero(root.left)) {
            return false;
        }
        if (!isZero(root.right)) {
            return false;
        }
        return true;
    }
}
